<template>
  <div>
      <el-button @click="showDialog"  type="primary" icon="el-icon-plus" style="margin-top: 20px"
      >添加</el-button
    >

    <el-table :data="advList" border style="width: 100%; margin-top: 20px">
      <el-table-column type="index" label="ID" width="150" align="center">
      </el-table-column>
      <el-table-column prop="url" label="广告图片"  align="center"> 
          <template slot-scope="{ row }">
            <img :src="`http://lfmini.hxcraft.top`+row.url" alt="" style="width: 100px" />
          </template>
      </el-table-column>
      <el-table-column prop="clickTime" label="点击次数" align="center"> </el-table-column>
      <el-table-column prop="expirationTime" label="到期时间" align="center"> </el-table-column>
      <el-table-column fixed="right" label="操作"  align="center">
        <template slot-scope="{row}">
          <el-button type="primary" icon="el-icon-edit" @click="showDialog(row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="deleteu(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>



    <!-- 分页 -->
    <el-pagination
      style="text-align: center; margin-top: 20px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[2, 3, 10]"
      :page-size="limit"
      layout="prev, pager, next, jumper,->,total,sizes"
      :total="total"
    >
    </el-pagination>

    <!-- 表单 -->
    <!-- //action="/dev-api/service_manage/file/upload" -->
    <el-dialog title="增加广告" 
    style="width:100"
    :visible.sync="dialogFormVisible"
    :before-close="close">
      <el-form :model="advForm" ref="addForm" >
        <el-form-item label="广告图片" label-width="100px" prop ="apicture">
          <el-upload
            class="avatar-uploader"
            action="https://lfcon.hxcraft.top/service_manage/file/upload"
            
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="advForm.url" :src="`http://lfmini.hxcraft.top`+advForm.url" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload_tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="点击次数" label-width="100px" prop = "click">
           <el-input-number v-model="advForm.clickTime" @change="handleChange" :min="0" :max="1000000" label="描述文字">
           </el-input-number>
        </el-form-item>
        <!-- <el-form-item label="广告到期时间" label-width="100px" prop = "lastTime">
          <el-col :span="8">
            <el-date-picker type="date" placeholder="选择日期" v-model="advForm.expirationTime" style="width: 100%;"></el-date-picker>
          </el-col>
          <el-col class="line" :span="2">---</el-col>
          <el-col :span="8">
            <el-time-picker placeholder="选择时间" v-model="advForm.expirationTime" style="width: 100%;"></el-time-picker>
          </el-col>
        </el-form-item> -->
        <span class="demonstration"><b>广告到期时间：</b></span>
          <el-date-picker
            v-model="advForm.expirationTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期时间"
            default-time="12:00:00">
          </el-date-picker>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="concel">取 消</el-button>
        <el-button type="primary" @click="save()"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import {getToken} from "@/utils/auth";
export default {
    name:"advList",
    data() {
      return {
        page: 1,
        limit: 10,
        total: 15,
        advList: [],
        dialogFormVisible:false,
        advForm:{
          url:"",
          clickTime:0,
          expirationTime:""
        },
        
      }
    },
    mounted(){
      this.getAdvList(this.page);

    },
    methods:{
      //显示表单
      showDialog(row){
              //该函数添加属性和编辑属性都会调用
              //编辑属性的时候会传入row（当前行的数据对象）
              //通过id属性判断当前回调函数的触发来源
              if(row.id){
                //只有编辑才能进入该区域
                //此处是引用值传递
                //...是浅拷贝，将当前row对象中的所有属性以及他们的值复制一份到tmForm中
                // alert(row.resType)
                this.advForm = {
                  ...row
                };

              }
                this.dialogFormVisible = true
        },
        close(){
          this.dialogFormVisible=false,
          this.advForm={
            url:"",
            clickTime:0,
            expirationTime:""
          }
        },

      //获取adv列表
      async getAdvList(page){        
            const {
                data: { total, items },
            } = await this.$API.adv.getAdvList(getToken(),page ? page : this.page, this.limit);
            this.total = total;
            if(page){
              this.page = page
            }
            // console.log(result);
            this.advList = items;
        },

       // 点击第几页
        handleCurrentChange(value) {
        //通过当前事件，可以知道用户点击了哪个页数
        this.page = value;
        //发送请求，获取对应页面的数据
        this.getAdvList(this.page);
        },

        //限制当前页面显示的数量
        handleSizeChange(value) {
        this.limit = value;
        this.getAdvList(this.page);
        },

        handleAvatarSuccess(res) {
            //由于用户通过input标签选中图片后，该图片就存储于浏览器内存中
            //以下代码是将内存中的图片，生成本地链接地址，用来展示
            // this.imageUrl = URL.createObjectURL(file.raw);\
            // alert(res.data[0].url)
            this.advForm.url =res.data[0].url;
            // console.log(advForm.url);
            
            // alert(this.proForm.picture)
            
            
        },

        beforeAvatarUpload(file) {
            const types = ['image/jpeg','image/jpg','image/png'];
            const isJPG = types.includes(file.type);
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        save(){
          //首先先校验数据的合法信
            this.$refs.addForm.validate(async(valid)  => {
            //valid代表表单的全部校验结果
            if (valid) {
              //1、收集请求所需要的数据
              //已经整理在userForm中，不需要在收集
              // alert(1)
              // this.advForm.resType =  Number(this.proForm.resType)
              try {
                    //2.发送请求
                    
                    await this.$API.adv.addOrUpdate(getToken(),this.advForm);
                    // console.log(this.proForm);
                    // alert(1)
                    //请求最新的品牌列表，由于添加功能无法知道在那一页，所以统一请求第一页
                    this.getAdvList(this.page);
                    //弹窗提示
                    //3.成功之后
                    // if(row.id){
                    //   this.$message({
                    //     message:'修改成功',
                    //     type:'success'
                    //   })
                    // }
                    this.$message({
                        message:'修改成功',
                        type: 'success'
                    });
                    //将添加框隐藏
                    this.dialogFormVisible = false
                    //清空当前dialog的内容
                    this.advForm = {
                      url:"",
                      clickTime:0,
                      expirationTime:""
                    }
                } catch (error) {
                  //4.失败之后
                    this.$message({
                        message: '修改失败',
                        type: 'info'
                    });
                   
                } 
            } else {
               this.dialogFormVisible = false
            //this.$message.info("保存失败")
            }
          });
           
        },

        concel(){
          this.dialogFormVisible = false
          this.advForm = {
            url:"",
            clickTime:0,
            expirationTime:""
         }
        },

        deleteu(row) {
        // alert(row.id)
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          //点击确定之后执行的代码
          //发送请求 
          try {
            //1.发送请求
              await this.$API.adv.deleteAdv(getToken(),row.id);
              this.$message({
              type: 'success',
              message: '删除成功!'
            });
            //请求最新列表
            //如果当前页面还有数据就请求当前页面
            //如果删除的是当前页面的最后一个数据则请求前一个夜间

            this.getAdvList(this.advList.length>1? this.page : this.page-1);
          } catch (error) {
              this.$message({
              type: 'info',
              message: '删除失败'
            });
          }   
        }).catch(() => {
            this.$message({
            type: 'info',
            message: '已取消删除'
          });        
        });
      }

    }
};
</script>

<style>
.avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
</style>